
package com.be.beadmin.device.impl;
import com.be.beadmin.basicData.repository.RoleRepository;
import com.be.beadmin.basicData.entity.Role;
import com.be.beadmin.basicData.entity.User;
import com.be.beadmin.basicData.repository.UserRepository;
import com.be.beadmin.common.entity.PageEntity;
import com.be.beadmin.device.entity.MaintenanceInfo;
import cn.hutool.core.util.ObjectUtil;
import com.be.beadmin.common.exception.BeadminException;
import com.be.beadmin.common.utils.JpaQueryBuilder;
import com.be.beadmin.common.utils.JpaSortBuilder;
//import com.be.beadmin.device.entity.MaintenanceInfo_;
import com.be.beadmin.device.entity.MaintenanceInfo_;
import com.be.beadmin.project.entity.Info;
import lombok.RequiredArgsConstructor;
import com.be.beadmin.device.mapper.MaintenanceInfoMapperEx;
import com.be.beadmin.device.repository.MaintenanceInfoRepository;
import com.be.beadmin.device.service.MaintenanceInfoService;
import com.be.beadmin.device.dto.input.MaintenanceInfoDto;
import com.be.beadmin.device.dto.output.MaintenanceInfoEx;
import com.be.beadmin.device.dto.input.MaintenanceInfoQueryCriteria;
import com.be.beadmin.device.mapper.MaintenanceInfoMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Order;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Set;

/**
* @description 服务实现
* @author zty
* @date 2023-08-01
**/
@Service
@RequiredArgsConstructor
public class MaintenanceInfoServiceImpl implements MaintenanceInfoService {

    @Autowired
    private  MaintenanceInfoRepository maintenanceInfoRepository;
    @Resource
    private  MaintenanceInfoMapper maintenanceInfoMapper;
    @Resource
    private  MaintenanceInfoMapperEx maintenanceInfoExMapper;
    @Autowired
    private UserRepository userRepository;
    @Autowired
    private RoleRepository roleRepository;

    @Override
    public Page<MaintenanceInfoEx> getMaintenanceInfoByPage(PageEntity pageEntity) {
            Pageable pageable = PageRequest.of(
            pageEntity.getCurrent() -1,
            pageEntity.getPageSize());
            Page<MaintenanceInfo> page = maintenanceInfoRepository.findAll((root, criteriaQuery, criteriaBuilder) -> {
                    List<Predicate> list = new ArrayList<>();
                    Predicate pre1 =   JpaQueryBuilder.getPredicate(root, pageEntity.getFilters(), criteriaBuilder);
                    list.add(pre1);
                    Predicate pre2 = criteriaBuilder.equal(root.get(MaintenanceInfo_.delete), 0); //过滤为0
                    list.add(pre2);
                    Predicate[] p = new Predicate[list.size()];
                    List<Order> orders = new ArrayList<>();
                    if(pageEntity.getSorters() != null && pageEntity.getSorters().size() > 0) {
                        orders = JpaSortBuilder.getPredicate(root, pageEntity.getSorters(), criteriaBuilder);
                        criteriaQuery.orderBy(orders);
                    } else {
                        criteriaQuery.orderBy(criteriaBuilder.desc(root.get(MaintenanceInfo_.createTime).as(Date.class)));
                    }
                    return  criteriaBuilder.and(list.toArray(p));
                    }
                    , pageable);
            Page<MaintenanceInfoEx> page1 = page.map(maintenanceInfoExMapper::toEntity);
            return page1;

    }

    @Override
    public void addMaintenanceInfo(MaintenanceInfoDto maintenanceInfoDto) {
            MaintenanceInfo result = maintenanceInfoRepository.findMaintenanceInfoByIdAndDelete(maintenanceInfoDto.getId(), 0);
            if(ObjectUtil.isNotEmpty(result)) {
                throw new BeadminException("MaintenanceInfo不存在,请重新查询");
            }
            MaintenanceInfo maintenanceInfo = maintenanceInfoMapper.toEntity(maintenanceInfoDto);
            maintenanceInfoRepository.save(maintenanceInfo);
    }

    @Override
    public void updateMaintenanceInfo(MaintenanceInfoDto maintenanceInfoDto) {
            MaintenanceInfo maintenanceInfo = maintenanceInfoRepository.findMaintenanceInfoById(maintenanceInfoDto.getId());
            maintenanceInfo = maintenanceInfoMapper.toEntity(maintenanceInfoDto);
            maintenanceInfoRepository.save(maintenanceInfo);
    }


    @Override
    public void delMaintenanceInfo(String id) {
        MaintenanceInfo maintenanceInfo = maintenanceInfoRepository.findMaintenanceInfoById(id);
        maintenanceInfo.setDelete(1);
        maintenanceInfoRepository.save(maintenanceInfo);
    }

    @Override
    public void delMaintenanceInfos (List<String> ids) { }

    @Override
    public MaintenanceInfo getMaintenanceInfoByIdentification(String identification) {
        MaintenanceInfo maintenanceInfo = maintenanceInfoRepository.findMaintenanceInfoByIdentificationAndDelete(identification, 0);
        if (maintenanceInfo == null) {
            throw new BeadminException("未找到该维修工单");
        }
        return maintenanceInfo;
    }

    @Override
    public MaintenanceInfo getMaintenanceInfoByCreateName(String createName) {
        MaintenanceInfo maintenanceInfo = maintenanceInfoRepository.findMaintenanceInfoByCreateNameAndDelete(createName, 0);
        if (maintenanceInfo == null) {
            throw new BeadminException("未找到该维修工单");
        }
        return maintenanceInfo;
    }

    @Override
    public MaintenanceInfo getMaintenanceInfoByAssignedTo(String assignedTo) {
        MaintenanceInfo maintenanceInfo = maintenanceInfoRepository.findMaintenanceInfoByAssignedToAndDelete(assignedTo, 0);
        if (maintenanceInfo == null) {
            throw new BeadminException("未找到该维修工单");
        }
        return maintenanceInfo;
    }

    @Override
    public MaintenanceInfo getMaintenanceInfoByAssignedToAndState(String assignedTo, String state) {
        MaintenanceInfo maintenanceInfo = maintenanceInfoRepository.findMaintenanceInfoByAssignedToAndStateAndDelete(assignedTo, state, 0);
        if (maintenanceInfo == null) {
            throw new BeadminException("未找到该维修工单");
        }
        return maintenanceInfo;
    }


    @Override
    public List<String> getMaintenanceCommissioners() {
        Role role = roleRepository.findRoleByCodeAndDelete("ROLE_Maintenance" , 0);
        String roleId = role.getId();
        List<String> userIds = userRepository.findUserIdsByRoleId(roleId);
        List<String> nameList = new ArrayList<>();
        User user = new User();
        for(String userId : userIds){
            user = userRepository.findUserByIdAndDelete(userId , 0);
            if (user!=null)
                nameList.add(user.getName());
        }
        return nameList;
    }

    @Override
    public Long getMaintenanceHours(MaintenanceInfo maintenanceInfo) {
        Date beginMaintenance = maintenanceInfo.getBeginMaintenance();
        Date endMaintenance = maintenanceInfo.getEndMaintenance();
        int result = beginMaintenance.compareTo(endMaintenance);
        if(result >= 0){
            throw new BeadminException("维修开始时间不能晚于维修结束时间");
        }
        Instant begin = beginMaintenance.toInstant();
        Instant end = endMaintenance.toInstant();
        Long hours = ChronoUnit.HOURS.between(begin , end);
        return hours;
    }

    @Override
    public void generateMaintenanceInfoByInspect(String faultDesc) {
        MaintenanceInfoDto maintenanceInfoDto = new MaintenanceInfoDto();
        maintenanceInfoDto.setFaultDesc(faultDesc);
        addMaintenanceInfo(maintenanceInfoDto);
    }

}